from flask import Blueprint, render_template, request, redirect, session
# 使用蓝图注册路由
ac = Blueprint("account", __name__)
# 导入自定义的数据库工具函数
from utils import dbUtil

@ac.route('/login', methods=['GET', 'POST'])
def login():
    # return "登录"
    if request.method == 'GET':
        return render_template("login.html")
    elif request.method == 'POST':
        role = request.form['role']
        mobile = request.form['mobile']
        password = request.form['pwd']
        # 输出字符串："您登录的参数为 role=?,mobile=?,password=?"
        print("您登录的参数为 role={},mobile={},password={}".format(role, mobile, password))

        # 去数据库校验
        result = dbUtil.fetch_one("select * from account_user where mobile = %s and password=%s and role=%s", [mobile, password, role])
        print(f"查询结果 list结构数据：{result}") # (1, '18617151926', '123456', 'jerry', 1)
        user_dict =  dbUtil.fetch_one_as_dict("select * from account_user where mobile = %s and password=%s and role=%s", [mobile, password, role])
        print(f"查询结果 dict结构数据：{user_dict}") # {'id': 1, 'mobile': '18617151926', 'password': '123456', 'real_name': 'jerry', 'role': 1}
        if user_dict:
            # 登录成功
            #return "登录成功"

            # 将登录成功的用户信息存入session
            session['user_info'] = {"role": user_dict['role'], "mobile": user_dict['mobile'], "id": user_dict['id'], "real_name": user_dict['real_name']}

            return redirect("/author_list") # 登录成功后重定向跳转到订单列表页面
        else:
            # 登录失败
            #return "登录失败"
            return render_template("login.html", error="用户名或密码错误")
    return "登录页面"


@ac.route('/register', methods=['GET', 'POST'])
def register():
    return "注册"


@ac.route('/users', methods=['GET', 'POST'])
def users():
    return "用户列表"
